from datetime import datetime
from flask import Flask
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields,validate
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:1@127.0.0.1:3306/mofangapp?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy()
db.init_app(app)

ma = Marshmallow()
ma.init_app(app)

class User(db.Model):
    __tablename__ = "tb_user"
    id = db.Column(db.Integer, primary_key=True, comment="主键ID")
    name = db.Column(db.String(255), index=True, comment="用户名")
    email = db.String(db.String(255))
    age = db.Column(db.Integer, comment="年龄")
    password = db.Column(db.String(255), comment="登录密码")
    mobile = db.Column(db.String(20), comment="手机号")

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.name)

class UserSchema(Schema):
    name = fields.String(validate=validate.Length(min=1))
    age = fields.Integer(required=True,validate=validate.Range(min=16,max=100))
    email = fields.String(validate=validate.Email())
    password = fields.Str(load_only=True,validate=validate.Length(min=6,max=16)) # 相当于只写字段 "write-only"
    mobile = fields.String(validate=validate.Regexp("^1[3-9]\d{9}$",error="手机号格式不正确!"))

@app.route("/")
def index():
    user_data = {"email":"xiaoming@qq.com","name": "小明", "age": 20,"password":"123456","mobile":"13312345678"}  # 报错
    us = UserSchema()
    # 反序列化
    instance = us.load(user_data)
    print(instance)
    return "hello"

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=5999)